package drone.basis.util;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class LogUtil {

	private static boolean FLAG;
	private static String ROOT;

	static {
		if ("linux".equalsIgnoreCase(System.getProperty("os.name"))) {
			ROOT = "/latch/logs";
			FLAG = false;
		} else {
			ROOT = "d:/latch/logs";
			FLAG = true;
		}
	}

	public static List<File> listLog(String filePath) {
		try {
			List<File> list = Arrays.asList(new File(ROOT + filePath + "/").listFiles());
			Collections.sort(list, new Comparator<File>() {
				public int compare(File f1, File f2) {
					return f2.getName().compareTo(f1.getName());
				}
			});
			return list;
		} catch (Exception e) {
			return null;
		}
	}

	public static String readLog(String filePath, String fileName) {
		String fileInfo = "";
		try {
			fileInfo = FileUtil.read(ROOT + filePath + "/", fileName);
		} catch (Exception e) {
			System.out.println("logging failure");
		}
		if (FLAG) {
			System.out.println(fileInfo);
		}
		return fileInfo;
	}

	public static void writeLog(String filePath, String fileName, String fileInfo) {
		if (FLAG) {
			System.out.println(fileInfo);
		}
		fileInfo = DateUtil.format(new Date(), "HHmmss") + " " + fileInfo + System.lineSeparator();
		try {
			FileUtil.append(ROOT + filePath + "/", fileName, fileInfo);
		} catch (Exception e) {
			System.out.println("logging failure");
		}
	}

}
